package net.xiangcaowuyu.dynamicdatasource.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.xiangcaowuyu.dynamicdatasource.annotation.DataSource;
import net.xiangcaowuyu.dynamicdatasource.datasource.DynamicDataSourceContextHolder;
import net.xiangcaowuyu.dynamicdatasource.domain.TableOne;
import net.xiangcaowuyu.dynamicdatasource.domain.TableTwo;
import net.xiangcaowuyu.dynamicdatasource.mapper.TableOneMapper;
import net.xiangcaowuyu.dynamicdatasource.mapper.TableTwoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/")
public class DynamicDatSourceController {

    private final Logger logger = LoggerFactory.getLogger(DynamicDatSourceController.class);

    @Resource
    TableOneMapper tableOneMapper;

    @Resource
    TableTwoMapper tableTwoMapper;

    @GetMapping
    public void test() throws Exception {
        logger.info("准备查询数据源1的数据");
        logger.info(tableOneMapper.selectList(new QueryWrapper<>()).get(0).getName());
        logger.info("准备查询数据源2的数据");
        DynamicDataSourceContextHolder.setDataSourceKey("dynamicDataSourceTwo");
        logger.info(tableTwoMapper.selectList(new QueryWrapper<>()).get(0).getName());
    }

    @DataSource(value = "dynamicDataSourceOne")
    @GetMapping("listTableOne")
    public List<TableOne> listTableOne() {
        return tableOneMapper.selectList(new QueryWrapper<>());
    }

    @DataSource(value = "dynamicDataSourceTwo")
    @GetMapping("listTableTwo")
    public List<TableTwo> listTableTwo(){
        return tableTwoMapper.selectList(new QueryWrapper<>());
    }

    @DataSource
    @GetMapping("tableList")
    public String tableList(){
        return "当前数据源为："+DynamicDataSourceContextHolder.getDataSourceKey();
    }
}
